//Sun 09 Oct 2011 11:48:24 PDT 
import java.util.*;
import java.util.regex.*;
import java.text.*;
import java.math.*;
import java.awt.geom.*;

public class PermissionTree {
	public Node root;

	public int[] findHome(String[] folders, String[] users) {
		int[] ret = new int[users.length];
		root = init(folders);
		// display(root);
		for (int i = 0; i < users.length; i++) {
			ret[i] = find(root, users[i]);
		}
		return ret;
	}

	public void display(Node node) {
		System.out.print(node.id + " : ");
		for (int i = 0; i < node.users.size(); i++)
			System.out.print(node.users.get(i) + ", ");
		System.out.println();
		for (int i = 0; i < node.next.size(); i++)
			display(node.next.get(i));
	}

	public int find(Node node, String s) {
		if (node == null)
			return -1;
		if (node.users.indexOf(s) != -1)
			return node.id;
		int count = 0;
		int id = -1;
		for (int i = 0; i < node.next.size(); i++) {
			int tmp = find(node.next.get(i), s);
			if (tmp != -1) {
				count++;
				id = tmp;
			}
		}
		if (count == 1)
			return id;
		if (count > 1)
			return node.id;
		return -1;
	}

	public Node init(String[] folders) {
		List<Node> list = new ArrayList<Node>();
		for (int i = 0; i < folders.length; i++) {
			list.add(new Node());
		}
		for (int i = 0; i < folders.length; i++) {
			list.get(i).id = i;
			int id = Integer.parseInt(folders[i].split(" ")[0]);
			// not self node.
			if (id != i) {
				list.get(id).next.add(list.get(i));
			}
			String[] names = folders[i].split(" ")[1].split(",");
			for (int j = 0; j < names.length; j++)
				list.get(i).users.add(names[j]);
		}
		return list.get(0);
	}
	// <%:testing-code%>
}

class Node {
	public int id;
	public List<String> users;
	public List<Node> next;

	public Node() {
		this.id = -1;
		this.users = new ArrayList<String>();
		this.next = new ArrayList<Node>();
	}
}

// Powered by [KawigiEdit] 2.0!
